<script setup lang="ts">
  import { getCurrentInstance, reactive, ref } from 'vue'
  import { UploadFilled } from '@element-plus/icons-vue'
  import { useUserStore } from '@/store/modules/user'
  import { UploadInstance } from 'element-plus'

  const { proxy }: any = getCurrentInstance()
  const UserStore = useUserStore()
  /*const baseUrl = ;*/

  const upload = reactive({
    // 弹出层标题（用户导入）
    title: '',
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的用户数据
    updateSupport: false,
    // 设置上传的请求头部
    headers: { Authorization: UserStore.token },
    // 上传的地址
    url: proxy.$getServerUrl() + '/system/user/importData',
  })

  // 是否显示弹出层（用户导入）
  const open = ref(false)
  const openResult = ref(false)
  const uploadRef = ref<UploadInstance>()
  const uploadResult = ref<UploadInstance>()
  let $emit = defineEmits(['getUserListPage'])
  const responseMessage = ref('')
  // show方法
  const show = () => {
    console.log('依梦', '用户导入')
    open.value = true
    upload.title = '用户导入'
  }

  // 下载模板
  const importTemplate = () => {
    // 调用接口
    proxy.$download(
      'system/user/importTemplate',
      {},
      `user_template_(用户导入模板)${new Date().getTime()}.xlsx`,
    )
  }

  // 文件上传中处理
  const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true
  }

  // 文件上传成功处理
  const handleFileSuccess = (response, file, fileList) => {
    // 关闭对话框，将上传处理变成等待变成false，清理文件，打开弹出提示，再次查询
    open.value = false
    upload.isUploading = false
    uploadRef.value?.clearFiles()
    openResult.value = true
    responseMessage.value = response.message
    $emit('getUserListPage')
  }

  // 提交上传
  const submitFileForm = () => {
    uploadRef.value!.submit()
  }

  // 关闭对话框的回调
  const close = () => {
    Object.keys(upload).forEach((key) => {
      if (key === 'isUploading') {
        upload[key] = false
      } else if (key === 'updateSupport') {
        upload[key] = false
      } else if (key === 'title') {
        upload[key] = ''
      }
    })
  }

  defineExpose({
    show,
  })
</script>

<template>
  <!-- 用户导入对话框 -->
  <el-dialog @close="close" :title="upload.title" v-model="open" width="400px" append-to-body>
    <el-upload
      ref="uploadRef"
      :limit="1"
      accept=".xlsx, .xls"
      :headers="upload.headers"
      :action="upload.url + '?updateSupport=' + upload.updateSupport"
      :disabled="upload.isUploading"
      :on-progress="handleFileUploadProgress"
      :on-success="handleFileSuccess"
      :auto-upload="false"
      drag
    >
      <el-icon class="el-icon--upload">
        <upload-filled />
      </el-icon>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>

      <template #tip>
        <div class="el-upload__tip text-center" style="text-align: center">
          <div class="el-upload__tip text-center">
            <el-form v-model="upload">
              <div class="checkbox-container">
                <el-checkbox v-model="upload.updateSupport" />
                <span class="checkbox-label">是否更新已经存在的用户数据</span>
              </div>
            </el-form>
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板
          </el-link>
        </div>
      </template>
    </el-upload>
    <template #footer class="dialog-footer">
      <el-button type="success" @click="submitFileForm">确 定</el-button>
      <el-button type="warning" @click="open = false">取 消</el-button>
    </template>
  </el-dialog>

  <!--结果展示框  -->
  <el-dialog v-model="openResult" title="Warning" width="30%" align-center ref="uploadResult">
    <template #title>
      <span class="el-dialog__title">导入结果</span>
    </template>
    <span v-html="responseMessage"></span>
    <span></span>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="openResult = false"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
  .checkbox-container {
    display: flex;
    align-items: center;
    text-align: center;
    margin-left: 25%;
  }

  .el-dialog__title {
    font-weight: bold;
  }
</style>
